package com.nuc.thread.threadpool;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantReadWriteLock;

import static java.lang.Thread.sleep;

/**
 * @author 诗酒趁年华
 * @version 1.0.0
 * @Description 读写锁：
 * @createTime 2021年08月14日 17:05:00
 */
@Slf4j
public class Test5 {
    public static void main(String[] args) {
        DateContainer dateContainer = new DateContainer(12);

        new Thread(()->{
            dateContainer.read();
        },"t1").start();

        new Thread(()->{
            dateContainer.write();
        },"t2").start();


    }


}

@Slf4j(topic = "DateContainer")
class DateContainer{
    private Object data;
    private ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public DateContainer(Object data) {
        this.data = data;
    }

    public Object read(){
        try{
            readWriteLock.readLock().lock();//获取读锁
            log.debug("获得读锁");
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.readLock().unlock();//释放读锁
            log.debug("释放读锁");
        }
        return data;
    }


    public void write(){
        try{
            readWriteLock.writeLock().lock();//获取写锁
            log.debug("获得写锁");
            sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            readWriteLock.writeLock().unlock();//释放读锁
            log.debug("释放写锁");
        }
    }
}
